<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button
        size="medium"
        type="primary"
        class="filter-item"
        style="font-weight: bold"
        >会员总数:{{ total }}</el-button
      >
      <el-input
        v-model="listQuery.username"
        clearable
        class="filter-item"
        style="width: 200px"
        :disabled="consumOpen"
        placeholder="请输入用户名"
      ></el-input>
      <el-select
        v-model="listQuery.userLevel"
        :disabled="consumOpen"
        placeholder="请选择会员等级"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in userListLevels"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <el-select
        v-model="listQuery.status"
        placeholder="请选择账号状态"
        :disabled="consumOpen"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in userListStatus"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-cascader
        :placeholder="$t('请选择收货地址')"
        class="filter-item"
        v-model="listQuery.regionIds"
        :options="countrys"
        @active-item-change="handleItemChange"
        :props="props"
        clearable
        filterable
      ></el-cascader>

      <el-date-picker
        v-model="listQuery.lastLoginTimeRange"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        :start-placeholder="$t('登录开始日期')"
        :end-placeholder="$t('登录结束日期')"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="datePickerShortcuts"
      />

      <el-date-picker
        v-model="listQuery.consumeTimeRange"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        :start-placeholder="$t('消费开始日期')"
        :end-placeholder="$t('消费结束日期')"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="datePickerShortcuts"
      />

      <el-button
        plain1
        class="filter-item"
        type="info"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("Search") }}
      </el-button>

      </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('Searching')"
      max-height="700"
      border
      fit
      :header-cell-style="{
        background: '#eef1f6',
        color: '#021629',
        top: '5px',
      }"
      highlight-current-row
      @sort-change="handleSort"
    >
      <!-- <el-table-column align="center" width="150px" :label="$t('Member_ID')" prop="id" sortable="custom" /> -->

      <el-table-column
        align="center"
        :label="$t('用户名')"
        width="280"
        prop="username"
        fixed="left"
        sortable="custom"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 2" type="warning">{{
            $t("用户注销")
          }}</el-tag>
          {{ maskStr(scope.row.username) }}
        </template>
      </el-table-column>

      <el-table-column
        width="160px"
        align="center"
        :label="$t('用户姓名')"
        prop="nickname"
      >
        <template slot-scope="scope">
          {{ maskStr(scope.row.nickname) }}
        </template>
      </el-table-column>
      <el-table-column
        label="注册类型"
        width="150px"
        align="center"
        prop="registerType"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.registerType === 0">{{ $t("手机注册") }}</el-tag>
          <el-tag v-if="scope.row.registerType === 1">{{ $t("邮箱注册") }}</el-tag>
          <el-tag v-if="scope.row.registerType === 2">{{ $t("Apple") }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        width="120px"
        align="center"
        property="avatar"
        :label="$t('头像')"
      >
        <template slot-scope="scope">
          <el-image
            preview-src-list
            style="border-radius: 15%; width: 50px"
            :src="scope.row.avatar"
            width="20"
            lazy
          >
            <div slot="error" class="image-slot">
              <i
                style="font-size: 30px"
                class="el-icon-picture-outline-round"
              ></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('性别')" prop="gender">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.gender == 0">{{ $t("其他") }}</el-tag>
          <el-tag v-if="scope.row.gender == 1">{{ $t("男") }}</el-tag>
          <el-tag v-if="scope.row.gender == 2">{{ $t("女") }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        width="150px"
        align="center"
        :label="$t('生日')"
        prop="birthday"
      />

      <el-table-column
        width="150px"
        align="center"
        :label="$t('手机号码')"
        prop="mobile"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("手机号码") }}
          <i class="el-icon-mobile-phone" style="color: #de700c"></i>
        </template>
        <template slot-scope="scope">
          <el-tag>{{ maskStr(scope.row.mobile) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        width="160px"
        align="center"
        :label="$t('邮箱')"
        prop="email"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("邮箱") }}
          <i class="el-icon-message" style="color: #de700c"></i>
        </template>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.email">{{ scope.row.email }}</el-tag>
          <span v-else></span>
          <!-- 如果邮箱字段为空，则显示空 -->
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('Point Operate')"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("Point Operate") }}
          <i class="el-icon-star-on" style="color: #e73171"></i>
        </template>
        <template slot-scope="scope">
          <el-row>
            <el-button
              type="warning"
              icon="el-icon-star-off"
              plain
              round
              v-permission="['GET /admin/p/member_member_update_point']"
              size="small"
              @click="handlePoints(scope.row)"
              v-if="scope.row.status == 0"
              >{{ $t("积分管理") }}
            </el-button>
          </el-row>
          <el-row style="padding-top: 10px">
            <el-button
              icon="el-icon-star-off"
              plain
              round
              v-permission="['GET /admin/p/member_member_point_point_detail']"
              type="primary"
              size="small"
              @click="getPointList(scope.row)"
              >{{ $t("积分详情") }}
            </el-button>
          </el-row>
        </template>
      </el-table-column>

      <el-table-column
        width="150px"
        align="center"
        :label="$t('会员等级')"
        prop="userLevel"
        sortable="custom"
      >
        <template slot-scope="scope">
          <el-tag>{{ formateLevelMember(scope.row) }}</el-tag>
        </template>
      </el-table-column>

      <!--      <el-table-column align="center" label="消费金额" prop="mobile"/>-->

      <el-table-column
        width="150px"
        align="center"
        :label="$t('账号状态')"
        prop="status"
        sortable="custom"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="success">{{
            statusDic[scope.row.status]
          }}</el-tag>
          <el-tag v-if="scope.row.status == 1" type="danger">{{
            statusDic[scope.row.status]
          }}</el-tag>
          <el-tag v-if="scope.row.status == 2" type="warning">{{
            statusDic[scope.row.status]
          }}</el-tag>
          <el-tag v-if="scope.row.status == 3" type="danger">{{
            statusDic[scope.row.status]
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        width="150px"
        align="center"
        :label="$t('可用积分')"
        prop="points"
      >
        <template slot-scope="scope">
          <el-tag type="danger">{{ scope.row.points.toFixed(0) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        width="200px"
        align="center"
        :label="$t('登录时间')"
        prop="lastLoginTime"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("登录时间") }}
          <i class="el-icon-time" style="color: #89e731"></i>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('Operate')"
        width="300"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("Operate") }}
          <i class="el-icon-setting" style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-row>
            <el-button
              type="primary"
              round
              icon="el-icon-edit"
              plain1
              v-permission="['GET /admin/p/member_member_edit']"
              size="small"
              @click="handleEdit(scope.row)"
              >{{ $t("Edit") }}
            </el-button>
            <el-button
              type="info"
              round
              icon="el-icon-refresh-right"
              v-permission="['GET /admin/p/member_member_resetpasswrod']"
              size="small"
              @click="handleReset(scope.row)"
              >{{ $t("重置密码") }}
            </el-button>
          </el-row>
          <el-row style="padding-top: 10px">
            <el-button
              icon="el-icon-s-promotion"
              round
              plain1
              v-permission="['GET /admin/p/member_member_issuecoupons']"
              type="success"
              size="small"
              @click="grantCoupon(scope.row)"
              >{{ $t("发放优惠券") }}
            </el-button>
            <el-button
              icon="el-icon-view"
              round
              plain1
              v-permission="['GET /admin/p/member_member_detail']"
              type="info"
              size="small"
              @click="handleDetail(scope.row)"
              >{{ $t("Details") }}
            </el-button>
            <el-button
              icon="el-icon-delete"
              round
              plain1
              v-permission="['GET /admin/p/member_member_deleted']"
              type="danger"
              size="small"
              @click="handleDeleted(scope.row)"
              >{{ $t("删除") }}
            </el-button>
            <!--            <el-button v-permission="['GET /admin/p/member_member_giveintegral']" type="primary" size="small" @click="handleIntegral(scope.row)">{{$t('赠送积分')}}</el-button>-->
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 重置密码对话框 -->
    <el-dialog :visible.sync="resetDialogVisible" :title="$t('重置密码')">
      <el-form
        ref="feedbackForm"
        :model="resetForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('填写新密码')" prop="newPwd">
          <el-input
            v-model="resetForm.newPwd"
            :placeholder="$t('新密码，不填则系统生成')"
          />
        </el-form-item>
        <el-form-item v-if="pwd" :label="$t('新密码')" prop="pwd">
          <el-input v-model="pwd" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          plain1
          round
          icon="el-icon-error"
          @click="resetDialogVisible = false"
          >{{ $t("Cancel") }}</el-button
        >
        <el-button
          plain1
          round
          icon="el-icon-success"
          type="primary"
          @click="resetConfirm"
          >{{ $t("Confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog :visible.sync="editDialogVisible" :title="$t('修改用户信息')">
      <el-form
        ref="editForm"
        :model="editForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('账号')" prop="username">
          <el-input v-model.number="editForm.username" />
        </el-form-item>
        <el-form-item :label="$t('性别')" prop="gender">
          <el-select v-model="editForm.gender" clearable>
            <el-option :value="0" :label="$t('其他')"></el-option>
            <el-option :value="2" :label="$t('女')"></el-option>
            <el-option :value="1" :label="$t('男')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('生日')" prop="birthday">
          <el-date-picker
            clearable
            class="filter-date-item"
            v-model="editForm.birthday"
            type="date"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('昵称')" prop="nickname">
          <el-input v-model.number="editForm.nickname" />
        </el-form-item>
        <el-form-item :label="$t('邮箱')" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item :label="$t('手机号码')" prop="mobile">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item :label="$t('用户状态')" prop="status">
          <template>
            <!-- 0 可用, 1 禁用, 2 注销 -->
            <el-tag effect="plain1" type="warning" v-if="editForm.status == 2"
              >{{ $t("已注销") }}
              <i class="el-icon-warning" style="color: #f8c564"></i
            ></el-tag>
            <el-switch
              v-else
              v-model="editForm.status"
              :active-value="0"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-form-item>
        <el-form-item :label="$t('注册时间')" prop="addTime">
          <el-input v-model="editForm.addTime" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          plain1
          round
          icon="el-icon-error"
          @click="editDialogVisible = false"
          >{{ $t("Cancel") }}</el-button
        >
        <el-button
          plain1
          round
          icon="el-icon-success"
          type="primary"
          @click="updateConfirm"
          >{{ $t("Confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 管理积分 -->
    <el-dialog
      :visible.sync="handlePointDialogVisible"
      :title="$t('修改用户积分')"
    >
      <el-form
        ref="handlePointForm"
        :model="handlePointForm"
        :rules="handlePointRules"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('操作类型')" prop="type">
          <el-radio-group v-model="handlePointForm.type" clearable>
            <el-radio :label="1">{{ $t("添加") }}</el-radio>
            <el-radio :label="2">{{ $t("减少") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('积分')" prop="points">
          <el-input-number
            v-model="handlePointForm.points"
            :min="0"
            :controls="false"
            :precision="0"
          >
          </el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          plain1
          round
          icon="el-icon-error"
          @click="handlePointDialogVisible = false"
          >{{ $t("Cancel") }}</el-button
        >
        <el-button
          plain1
          round
          icon="el-icon-success"
          type="primary"
          @click="doHandlePoints"
          >{{ $t("Confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="getPointDialogVisible"
      :title="$t('积分列表')"
      width="60%"
    >
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-select
          v-model="getPointQuery.type"
          clearable
          class="filter-item"
          :placeholder="$t('请选择积分操作类型')"
        >
          <el-option
            v-for="item in pointListTypes"
            :value="item.value"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-button
          plain1
          type="info"
          class="filter-item"
          icon="el-icon-search"
          @click="doGetPointList"
          >{{ $t("Search") }}</el-button
        >
      </div>

      <!-- 查询结果 -->
      <el-table
        ref="getPointTable"
        v-loading="getPointIndexLoading"
        :data="pointList"
        :element-loading-text="$t('Searching')"
        row-key="id"
        border
        fit
        highlight-current-row
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          type="index"
          :index="getPointIndex"
          width="50"
        ></el-table-column>
        <el-table-column
          align="center"
          :label="$t('变动时间')"
          prop="addTime"
        />
        <el-table-column
          align="center"
          min-width="50"
          :label="$t('类型')"
          prop="type"
        >
          <template slot-scope="scope">
            <el-tag>{{ formateType(scope.row.useType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="70"
          :label="$t('变动积分')"
          prop="changePoints"
        >
          <template slot-scope="scope">
            <el-tag>{{ scope.row.changePoints.toFixed(0) }}</el-tag>
          </template>
        </el-table-column>
        <!--   <el-table-column align="center" :label="$t('商品名称')" prop="goodsName" >
            <template slot-scope="scope">
              <el-tag v-for=" item in scope.row.goodsName">{{ item }}</el-tag>
            </template>
          </el-table-column>-->
        <el-table-column
          align="center"
          :label="$t('商店名称')"
          prop="shopName"
        />
      </el-table>

      <pagination
        v-show="pointListTotal > 0"
        :total="pointListTotal"
        :page.sync="getPointQuery.page"
        :limit.sync="getPointQuery.limit"
        @pagination="getPointListByPage"
      />

      <div slot="footer" class="dialog-footer">
        <el-button
          plain1
          round
          icon="el-icon-error"
          @click="getPointDialogVisible = false"
          >{{ $t("Cancel") }}</el-button
        >
        <el-button
          plain1
          round
          icon="el-icon-success"
          @click="getPointDialogVisible = false"
          type="primary"
          >{{ $t("Confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="grantCouponDialogVisible"
      :title="$t('发放优惠券')"
    >
      <el-form
        ref="handlePointForm"
        :model="grantCouponForm"
        :rules="grantCouponRules"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('优惠券')" prop="selectCouponId">
          <el-select v-model="grantCouponForm.selectCouponId">
            <el-option
              v-for="item in extenCouponLists"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('发放数量')" prop="num">
          <el-input
            v-model.number="grantCouponForm.num"
            :min="0"
            :required="true"
          >
          </el-input>
        </el-form-item>

        <el-form-item :label="$t('发放原因')" prop="remark">
          <el-input v-model="grantCouponForm.remark"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          plain1
          round
          icon="el-icon-error"
          @click="grantCouponDialogVisible = false"
          >{{ $t("Cancel") }}</el-button
        >
        <el-button
          plain1
          round
          icon="el-icon-success"
          type="primary"
          @click="doGrantExtenCoupon"
          >{{ $t("Confirm") }}</el-button
        >
      </div>
    </el-dialog>

    <!--    <el-dialog :visible.sync="submitDialogVisible" :title="$t('Confirm')">-->
    <!--      <div class="app-container">{{$t('保存完之后无法修改，确认保存盘点')}}？</div>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="submitDialogVisible = false">{{$t('Cancel')}}</el-button>-->
    <!--        <el-button @click="submit" type="primary">{{$t('Confirm')}}</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import {
  fetchList,
  resetUserPwd,
  updateIntegral,
  updateUser,
  userRemove,
} from "@/api/user";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { toLine } from "@/utils/stringConvert";
import { listCountryRegion, listSubRegion } from '@/api/region'
import {
  grantExtenCoupon,
  levelMemberList,
  pointDetail,
  updatePoint,
} from "../../api/user";
import { extenCouponList } from "../../api/coupon";
import { formatDate } from "@/utils/date";
import {datePickerShortcuts} from "../../utils/date";

export default {
  name: "User",
  components: { Pagination },
  data() {
    return {
      datePickerShortcuts,
      list: null,
      total: 0,
      listLoading: true,
      levelMembers: [],
      addressList: [],
      totalLastTime: [],
      totalUpdateTime: [],
      //消费开始时间控制
      consumOpen: false,
      /**
       * 列表查询参数对象，包含用于向后端发送查询请求的各种参数。
       */
      regionIdList:[],
      countrys:[],
      props: {
        value:'id',
        label: 'nameEn',
        children: 'children',
        checkStrictly: true
      },
      listQuery: {
        //当前页码，默认为 1
        page: 1,
        //每页显示的条目数，默认为 20
        limit: 20,
        //用户名，用于查询特定用户名的用户，默认为 undefined
        username: undefined,
        //手机号码，用于查询特定手机号码的用户，默认为 undefined
        mobile: undefined,
        //区域ID，用于查询特定区域的用户，默认为 undefined
        regionIds: [],
        //最后登录时间的起始日期，默认为 undefined
        lastLoginTimeRange: [],
        //消费时间的起始日期，默认为 undefined
        consumeTimeRange: [],
        //用户等级，用于查询特定等级的用户，默认为 undefined
        userLevel: undefined,
        //用户状态，用于查询特定状态的用户，默认为 undefined
        status: undefined,
      },

      pointListTypes: [
        {
          value: 1,
          name: "管理台增加减少",
        },
        {
          value: 2,
          name: "邀请获得积分",
        },
        {
          value: 3,
          name: "购买订阅",
        },
        {
          value: 4,
          name: "购买付费会员",
        },
        {
          value: 5,
          name: "积分兑换商品",
        },
        {
          value: 6,
          name: "退还「积分退款」",
        },
        {
          value: 7,
          name: "退款「订单退款",
        },
        {
          value: 8,
          name: "余额支付订单",
        },
        {
          value: 9,
          name: "礼物卡支付订单",
        },
      ],
      userListLevels: [],
      userListStatus: [
        {
          value: 0,
          name: "可用",
        },
        {
          value: 1,
          name: "禁用",
        },
        {
          value: 2,
          name: "注销",
        },
        {
          value: 3,
          name: "冻结",
        },
      ],
      handlePointRules: {
        type: [
          {
            required: true,
            message: this.$t("Operate_type_cannot_be_empty"),
            trigger: "blur",
          },
        ],
        points: [
          {
            required: true,
            message: this.$t("Points_cannot_be_empty"),
            trigger: "blur",
          },
        ],
      },
      grantCouponRules: {},
      getPointQuery: {
        page: 1,
        limit: 20,
        sort: "add_time",
        order: "desc",
        type: undefined,
      },
      formInline: {
        levelMemberName: undefined,
        page: 1,
        limit: 20,
        sort: "add_time",
        order: "desc",
      },
      getPointIndexLoading: false,
      pointList: [],
      handleId: undefined,
      downloadLoading: false,
      genderDic: ["", this.$t("其他"), this.$t("女"), this.$t("男")],
      levelDic: [
        this.$t("普通会员"),
        this.$t("白银会员"),
        this.$t("黄金会员"),
        this.$t("铂金会员"),
        this.$t("钻石会员"),
      ],
      statusDic: [
        this.$t("Usable"),
        this.$t("禁用"),
        this.$t("注销"),
        this.$t("冻结"),
      ],
      resetDialogVisible: false,
      resetForm: {
        userId: undefined,
        newPwd: undefined,
      },
      pointListTotal: 0,
      pwd: undefined,

      integralDialogVisible: false,
      integralForm: {
        userId: undefined,
        integral: undefined,
      },
      integralFormRules: {
        integral: [{ required: true, trigger: "blur" }],
      },
      editDialogVisible: false,
      handlePointDialogVisible: false,
      getPointDialogVisible: false,
      grantCouponDialogVisible: false,
      editForm: {},
      handlePointForm: {},
      grantCouponForm: {},
      grantUserId: undefined,
      extenCouponLists: [],
    };
  },
  created() {
    this.getList();
    this.getLevelMember();
    this.getUserLevel();
    this.getCountrys()
  },
  methods: {

    /**
     * 处理选项变更事件，根据选项的值获取子地区数据并更新到相应的父级地区对象中
     * @param {Array} val - 选项的值，包含地区ID路径
     */
    handleItemChange(val) {
      // 获取路径步数
      let step = val.length;
      // 构建查询参数
      let query = {
        id: val[val.length - 1],
        type: 1
      };
      // 调用接口获取子地区数据
      listSubRegion(query).then(response => {
        // 根据路径查找父级地区对象
        let result = this.findObject(this.countrys, val);
        // 遍历子地区数据
        response.data.data.list.forEach(child => {
          // 根据步数决定是否为子地区对象设置默认值
          if (step <= 1) {
            result.children.push(this._.defaults(child, { children: [] }));
          } else {
            result.children.push(child);
          }
        });
      });
    },

    /**
     * 在数组中根据指定的id路径查找对象
     * @param {Array} arr - 要查找的数组
     * @param {Array} ids - 要查找的id路径
     * @returns {Object|undefined} - 返回找到的对象，如果未找到则返回undefined
     */
    findObject(arr, ids) {
      // 遍历数组
      for (let i = 0; i <= arr.length - 1; i++) {
        let obj = arr[i];
        // 如果ids数组长度为1且当前对象的id与ids中的id相等，则返回当前对象
        if (ids.length == 1 && obj.id == ids[0]) {
          return obj;
        } else if (obj.id == ids[0]) {
          // 如果当前对象的id与ids中的id相等，则递归调用findObject查找子对象
          ids.shift();
          return this.findObject(obj.children, ids);
        }
      }
    },


    /**
     * 获取国家列表并设置到组件的数据中
     */
    getCountrys() {
      // 调用后端接口获取国家列表数据
      listCountryRegion().then(response => {
        // 对返回的数据进行处理，设置到组件的数据中
        this.countrys = response.data.data.list.map(function(country) {
          return _.defaults(country, { children: [] });
        });
      });
    },

    getList() {
      this.listLoading = true;
      fetchList(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },

    getLevelMember() {
      var data = {};
      levelMemberList(data)
        .then((res) => {
          // console.log('会员等级列表',res.data.data)
          this.levelMembers = res.data.data.list;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },

    getExtenCouponList() {
      extenCouponList().then((response) => {
        this.extenCouponLists = response.data.data.list;
      });
    },
    formateLevelMember(row) {
      for (let lengthKey in this.levelMembers) {
        if (this.levelMembers[lengthKey].id == row.userLevel) {
          return this.levelMembers[lengthKey].name;
        }
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    grantCoupon(row) {
      this.grantUserId = row.id;
      this.grantCouponDialogVisible = true;
      this.getExtenCouponList();
    },
    doGrantExtenCoupon() {
      this.grantCouponForm.userId = this.grantUserId;
      grantExtenCoupon(this.grantCouponForm)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: this.$t("优惠券发放成功!"),
          });
          this.grantCouponDialogVisible = false;
          this.getList();
          this.getExtenCouponList();
        })
        .catch((response) => {
          this.$notify.error({
            title: this.$t("Failed"),
            message: this.$t(response.data.errmsg),
          });
        });

      this.grantCouponForm.selectCouponId = undefined;
      this.grantCouponForm.num = undefined;
      this.grantCouponForm.remark = undefined;
    },
    handleDetail(row) {
      this.$router.push({ path: "/user/overview", query: { id: row.id } });
    },
    handleDeleted(row) {
      this.$confirm(
        this.$t("此操作将永久删除该用户, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(() => {
          userRemove(row.id)
            .then((res) => {
              this.integralDialogVisible = false;
              this.$notify.success({
                title: this.$t("Success!"),
                message: this.$t("Success!"),
              });
              this.handlePointDialogVisible = false;
              this.getList();
            })
            .catch((response) => {
              this.$notify.error({
                title: this.$t("Failed"),
                message: this.$t(response.data.errmsg),
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除"),
          });
        });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["用户名", "手机号码", "性别", "生日", "状态"];
        const filterVal = [
          "username",
          "mobile",
          "gender",
          "birthday",
          "status",
        ];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, "用户信息");
        this.downloadLoading = false;
      });
    },
    handleSort(item) {
      // console.log(item);
      if (item.order == "ascending") {
        this.listQuery.order = "asc";
      } else if (item.order == "descending") {
        this.listQuery.order = "desc";
      }
      this.listQuery.sort = toLine(item.prop);
      this.handleFilter();
    },
    handleReset(row) {
      this.resetDialogVisible = !this.resetDialogVisible;
      this.resetForm.userId = row.id;
      this.resetForm.newPwd = undefined;
      this.pwd = undefined;
    },
    handlePoints(row) {
      this.handleId = row.id;
      this.handlePointDialogVisible = true;
    },
    doHandlePoints() {
      this.handlePointForm.userId = this.handleId;
      this.$refs["handlePointForm"].validate((valid) => {
        if (valid) {
          updatePoint(this.handlePointForm)
            .then((response) => {
              this.integralDialogVisible = false;
              this.$notify.success({
                title: this.$t("Success!"),
                message: this.$t("Success!"),
              });
              this.handlePointDialogVisible = false;
              this.getList();
            })
            .catch((response) => {
              this.$notify.error({
                title: this.$t("Failed"),
                message: this.$t(response.data.errmsg),
              });
            });
        }
      });
    },
    getPointList(row) {
      this.pointUserId = row.id;
      this.getPointDialogVisible = true;
      this.doGetPointList();
    },
    getPointListByPage() {
      this.getPointDialogVisible = true;
      this.doGetPointList();
    },
    formateType(type) {
      for (let pointListTypesKey in this.pointListTypes) {
        if (type == this.pointListTypes[pointListTypesKey].value) {
          return this.pointListTypes[pointListTypesKey].name;
        }
      }
    },
    doGetPointList() {
      this.getPointQuery.userId = this.pointUserId;
      pointDetail(this.getPointQuery).then((response) => {
        const res = response.data.data;
        this.pointList = res.list;
        this.pointListTotal = res.total;
      });
    },
    resetConfirm() {
      resetUserPwd(this.resetForm)
        .then((response) => {
          this.resetDialogVisible = false;

          this.$alert(
            this.$t("新密码") + ":" + response.data.data,
            this.$t("重置成功"),
            {
              confirmButtonText: "确定",
            }
          );
        })
        .catch((response) => {
          this.$notify.error({
            title: this.$t("Failed"),
            message: this.$t(response.data.errmsg),
          });
        });
    },
    handleIntegral(row) {
      this.integralDialogVisible = !this.integralDialogVisible;
      this.integralForm.userId = row.id;
      this.integralForm.integral = undefined;
    },
    integralConfirm() {
      this.$refs["integraForm"].validate((valid) => {
        if (valid) {
          this.$confirm(
            this.$t("是否") +
              this.$t("赠送积分") +
              ":" +
              this.integralForm.integral +
              "?",
            this.$t("Hint"),
            {
              confirmButtonText: this.$t("Confirm"),
              cancelButtonText: this.$t("Cancel"),
              type: "warning",
            }
          ).then(() => {
            this.doUpdateIntegral();
          });
        }
      });
    },
    doUpdateIntegral() {
      updateIntegral(this.integralForm)
        .then((response) => {
          this.integralDialogVisible = false;
          this.$notify.success({
            title: this.$t("Success!"),
            message: this.$t("Success!"),
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: this.$t("Failed"),
            message: this.$t(response.data.errmsg),
          });
        });
    },
    handleEdit(row) {
      this.editDialogVisible = !this.editDialogVisible;
      this.editForm = row;
    },
    updateConfirm() {
      updateUser(this.editForm)
        .then((response) => {
          this.editDialogVisible = false;
          this.$notify.success({
            title: this.$t("Success!"),
            message: this.$t("Success!"),
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: this.$t("Failed"),
            message: this.$t(response.data.errmsg),
          });
        });
    },
    maskStr(str) {
      if (str) {
        return str.substr(0, 5) + "****" + str.substr(7, str.length);
      } else {
        return "----- -----";
      }
    },
    getIndex(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.limit;
    },
    getPointIndex(index) {
      return (
        index + 1 + (this.getPointQuery.page - 1) * this.getPointQuery.limit
      );
    },
    getUserLevel() {
      levelMemberList(this.formInline)
        .then((res) => {
          this.userListLevels = res.data.data.list;
        })
        .catch(() => {
          this.userListLevels = [];
        });
    },
    consumOpenFlag() {
      this.listQuery = {};
      if (
        !Array.isArray(this.totalUpdateTime) ||
        this.totalUpdateTime.length === 0
      ) {
        this.consumOpen = false;
      } else {
        this.consumOpen = true;
      }
    },
  },
};
</script>
